package com.example.inventoryapp.ui.item

import android.content.Context
import android.util.Log
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.calculateEndPadding
import androidx.compose.foundation.layout.calculateStartPadding
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import com.example.inventoryapp.InventoryTopAppBar
import com.example.inventoryapp.R
import com.example.inventoryapp.data.Item
import com.example.inventoryapp.ui.navigation.NavigationDestination
import com.example.inventoryapp.ui.theme.InventoryAppTheme
import com.example.inventoryapp.InventoryTopAppBar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.io.PrintWriter
import java.io.StringWriter
import java.util.Date
import java.util.Locale

// 添加在文件顶部（类外部）
object CrashReporter {
    private const val TAG = "CRASH_REPORTER"

    fun reportCrash(context: Context, e: Throwable, location: String) {
        try {
            val stackTrace = getStackTrace(e)
            val deviceInfo = getDeviceInfo()
            val time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date())

            val report = """
                |======= CRASH REPORT =======
                |Location: $location
                |Time: $time
                |
                |=== STACK TRACE ===
                |$stackTrace
                |
                |=== DEVICE INFO ===
                |$deviceInfo
                |======= END REPORT =======
                |
            """.trimMargin()

            Log.e(TAG, report)

            // 在后台线程保存崩溃日志
            saveToFile(context, report)
        } catch (logEx: Exception) {
            Log.e(TAG, "记录崩溃时出错", logEx)
        }
    }

    private fun getStackTrace(e: Throwable): String {
        val sw = StringWriter()
        val pw = PrintWriter(sw)
        e.printStackTrace(pw)
        return sw.toString()
    }

    private fun getDeviceInfo(): String {
        return """
            |Brand: ${android.os.Build.BRAND}
            |Device: ${android.os.Build.DEVICE}
            |Model: ${android.os.Build.MODEL}
            |Product: ${android.os.Build.PRODUCT}
            |Android SDK: ${android.os.Build.VERSION.SDK_INT}
            |Android Release: ${android.os.Build.VERSION.RELEASE}
        """.trimMargin()
    }

    private fun saveToFile(context: Context, report: String) {
        try {
            val file = File(context.filesDir, "crashes.log")
            FileOutputStream(file, true).use { fos ->
                fos.write(report.toByteArray())
                fos.write("\n\n".toByteArray()) // 分隔符
            }
        } catch (e: Exception) {
            Log.e(TAG, "保存崩溃日志失败", e)
        }
    }
}

object ItemDetailsDestination : NavigationDestination {
    override val route = "item_details"
    override val titleRes = R.string.item_detail_title
    const val itemIdArg = "itemId"
    val routeWithArgs = "$route/{$itemIdArg}"
}

//  在 ItemDetailsScreen Composable 中添加异常处理
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ItemDetailsScreen(
    navigateToEditItem: (Int) -> Unit,
    navigateBack: () -> Unit,
    modifier: Modifier = Modifier
) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()

    Scaffold(
        topBar = {
            InventoryTopAppBar(
                title = stringResource(ItemDetailsDestination.titleRes),
                canNavigateBack = true,
                navigateUp = navigateBack

            )
        }, floatingActionButton = {
            FloatingActionButton(
                onClick = {
                    try {
                        navigateToEditItem(0)
                    } catch (e: Exception) {
                        // 捕获并报告异常
                        Log.e("FAB_CLICK", "添加按钮点击异常", e)

                        // 在协程中处理崩溃报告，避免阻塞UI
                        scope.launch(Dispatchers.IO) {
                            CrashReporter.reportCrash(context, e, "FloatingActionButton-click")
                        }

                        // 可选：显示错误提示
                        // 可以使用 Snackbar 或 Toast，这里需要额外的状态管理

                    }
                },
                shape = MaterialTheme.shapes.medium,
                modifier = Modifier.padding(dimensionResource(id = R.dimen.padding_large))
            ) {
                Icon(
                    imageVector = Icons.Default.Edit,
                    contentDescription = stringResource(R.string.edit_item_title),
                )
            }
        },
        modifier = modifier
    ) { innerPadding ->
        ItemDetailsBody(
            itemDetailsUiState = ItemDetailsUiState(),
            onSellItem = {},
            onDelete = {},
            modifier = Modifier
                .padding(
                    start = innerPadding.calculateStartPadding(LocalLayoutDirection.current),
                    end = innerPadding.calculateEndPadding(LocalLayoutDirection.current),
                    top = innerPadding.calculateTopPadding()
                )
                .verticalScroll(rememberScrollState()),
            scope = scope,      // 传入scope
            context = context    // 传入context
        )
    }
}


// 在 ItemDetailsBody 中的按钮也添加异常处理
@Composable
private fun ItemDetailsBody(
    itemDetailsUiState: ItemDetailsUiState,
    onSellItem: () -> Unit,
    onDelete: () -> Unit,
    modifier: Modifier = Modifier,
    scope: CoroutineScope, // 新增
    context: Context       // 新增
) {
    Column(
        modifier = modifier.padding(dimensionResource(id = R.dimen.padding_medium)),
        verticalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.padding_medium))
    ) {
        var deleteConfirmationRequired by rememberSaveable { mutableStateOf(false) }

        ItemDetails(
            item = itemDetailsUiState.itemDetails.toItem(),
            modifier = Modifier.fillMaxWidth()
        )
        // 为销售按钮添加异常处理
        Button(
            onClick = {
                try {
                    onSellItem
                } catch (e: Exception) {
                    Log.e("SELL_BUTTON", "销售按钮点击异常", e)
                    scope.launch(Dispatchers.IO) {
                        CrashReporter.reportCrash(context, e, "SellButton-click")
                    }
                }
            },
            modifier = Modifier.fillMaxWidth(),
            shape = MaterialTheme.shapes.small,
            enabled = true
        ) {
            Text(stringResource(R.string.sell))
        }
        OutlinedButton(
            onClick = {
                try {
                    deleteConfirmationRequired = true
                } catch (e: Exception) {
                    Log.e("DELETE_BUTTON", "删除按钮点击异常", e)
                    scope.launch(Dispatchers.IO) {
                        CrashReporter.reportCrash(context, e, "DeleteButton-click")
                    }
                }
            },
            shape = MaterialTheme.shapes.small,
            modifier = Modifier.fillMaxWidth()
        ) {
            Text(stringResource(R.string.delete))
        }
        if (deleteConfirmationRequired) {
            DeleteConfirmationDialog(
                onDeleteConfirm = {
                    try {
                        deleteConfirmationRequired = false
                        onDelete()
                    } catch (e: Exception) {
                        Log.e("DELETE_CONFIRM", "删除确认异常", e)
                        scope.launch(Dispatchers.IO) {
                            CrashReporter.reportCrash(context, e, "DeleteConfirmation")
                        }
                    }
                },
                onDeleteCancel = {
                    try {
                        deleteConfirmationRequired = false
                    } catch (e: Exception) {
                        Log.e("DELETE_CANCEL", "删除取消异常", e)
                        scope.launch(Dispatchers.IO) {
                            CrashReporter.reportCrash(context, e, "DeleteCancel")
                        }
                    }
                },
                modifier = Modifier.padding(dimensionResource(id = R.dimen.padding_medium))
            )
        }
    }
}

@Composable
fun ItemDetails(
    item: Item, modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier,
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.primaryContainer,
            contentColor = MaterialTheme.colorScheme.onPrimaryContainer
        )
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(dimensionResource(id = R.dimen.padding_medium)),
            verticalArrangement = Arrangement.spacedBy(
                dimensionResource(id = R.dimen.padding_medium)
            )
        ) {
            ItemDetailsRow(
                labelResID = R.string.item,
                itemDetail = item.name,
                modifier = Modifier.padding(
                    horizontal = dimensionResource(id = R.dimen.padding_medium)
                )
            )
            ItemDetailsRow(
                labelResID = R.string.quantity_in_stock,
                itemDetail = item.quantity.toString(),
                modifier = Modifier.padding(
                    horizontal = dimensionResource(id = R.dimen.padding_medium)
                )
            )
            ItemDetailsRow(
                labelResID = R.string.price,
                itemDetail = item.formatedPrice(),
                modifier = Modifier.padding(
                    horizontal = dimensionResource(id = R.dimen.padding_medium)
                )
            )
        }
    }
}

@Composable
private fun ItemDetailsRow(
    @StringRes labelResID: Int, itemDetail: String, modifier: Modifier = Modifier
) {
    Row(modifier = modifier) {
        Text(stringResource(labelResID))
        Spacer(modifier = Modifier.weight(1f))
        Text(text = itemDetail, fontWeight = FontWeight.Bold)
    }
}

@Composable
private fun DeleteConfirmationDialog(
    onDeleteConfirm: () -> Unit,
    onDeleteCancel: () -> Unit,
    modifier: Modifier = Modifier
) {
    AlertDialog(
        onDismissRequest = { /* Do nothing */ },
        title = { Text(stringResource(R.string.attention)) },
        text = { Text(stringResource(R.string.delete_question)) },
        modifier = modifier,
        dismissButton = {
            TextButton(onClick = onDeleteCancel) {
                Text(stringResource(R.string.no))
            }
        },
        confirmButton = {
            TextButton(onClick = onDeleteConfirm) {
                Text(stringResource(R.string.yes))
            }
        })
}

@Preview(showBackground = true)
@Composable
fun ItemDetailsScreenPreview() {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()

    InventoryAppTheme {
        ItemDetailsBody(
            ItemDetailsUiState(
                outOfStock = true,
                itemDetails = ItemDetails(1, "Pen", "$100", "10")
            ),
            onSellItem = {},
            onDelete = {},
            scope = scope,      // 传入scope
            context = context    // 传入context
        )
    }
}
